package com.blog.serlvet;

import com.alibaba.fastjson.JSONObject;
import com.blog.bean.BaseResponse;
import com.blog.bean.User;
import com.blog.dao.UserDao;
import com.blog.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

public class UserInfoServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = LoginUtil.checkApiLogin(session, resp);
        if (user == null) {
            return;
        }

        String nick = req.getParameter("nick");
        String sign = req.getParameter("sign");

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        if (nick == null
                || nick.length() < 1
                || nick.length() > 20) {
            out.println(JSONObject.toJSONString(new BaseResponse(400, "昵称不正确", null)));
            return;
        }

        if (sign == null) {
            sign = "";
        }

        if (sign.length() > 500) {
            out.println(JSONObject.toJSONString(new BaseResponse(400, "个性签名太长啦", null)));
            return;
        }

        UserDao userDao = new UserDao();
        try {
            user.setNick(nick);
            user.setSign(sign);
            session.setAttribute("user", user);
            userDao.updateUser(nick, sign, user.getId());
            out.println(JSONObject.toJSONString(new BaseResponse(200, "用户信息更新成功", null)));
            return;
        } catch (SQLException e) {
            resp.sendError(500, "用户信息更新出错");
        }
    }
}
